package com.system.permissiondemo.util;


import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;

/**
* @Description:    json与类转换工具
* @Author:         Joe
* @CreateDate:     2020/3/25 11:22
*/
@Slf4j
public class JsonMapper {

    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
       //config
       objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
       objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
       objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
       objectMapper.setSerializationInclusion(org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion.NON_EMPTY);
    }

    /**
     * 对象转换String
     * @param src
     * @param <T>
     * @return
     */
    public static <T> String objToString(T src){
        if (src == null){
            return null;
        }
        try {
            return src instanceof String ? (String) src :objectMapper.writeValueAsString(src);
        }catch (Exception e){
            log.warn("对象转换String异常,error:{}",e);
            return null;
        }
    }

    /**
     * String转换对象
     * @param src
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T stringToObj(String src, TypeReference<T> typeReference){
        if (src == null || typeReference == null){
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src,typeReference));
        }catch (Exception e){
            log.warn("String转换对象异常,String:{},TypeReference<T>:{},error:{}",src,typeReference.getType(),e);
            return null;
        }
    }
}
